package com.example.examapp

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.content.Intent
import android.app.Activity
import android.net.Uri
import androidx.annotation.NonNull
import io.flutter.Log
import java.io.File
import java.io.FileOutputStream
import android.content.Context
import android.provider.OpenableColumns

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.example.examapp/file_select"
    private val PICK_EXCEL_FILE_REQUEST_CODE = 1001
    private var pendingResult: MethodChannel.Result? = null

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "pickExcelFile") {
                pendingResult = result
                pickExcelFile()
            } else {
                result.notImplemented()
            }
        }
    }

    private fun pickExcelFile() {
        try {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                putExtra(Intent.EXTRA_MIME_TYPES, arrayOf(
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
                    "application/vnd.ms-excel" // .xls
                ))
            }
            startActivityForResult(intent, PICK_EXCEL_FILE_REQUEST_CODE)
        } catch (e: Exception) {
            Log.e("FileSelector", "无法打开文件选择器: ${e.message}")
            pendingResult?.error("FILE_PICKER_ERROR", "无法打开文件选择器", e.message)
            pendingResult = null
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        
        if (requestCode == PICK_EXCEL_FILE_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null && data.data != null) {
                val uri = data.data!!
                val filePath = copyUriToExternalFilesDir(uri)
                if (filePath != null) {
                    pendingResult?.success(filePath)
                } else {
                    pendingResult?.error("FILE_SAVE_ERROR", "无法保存文件", null)
                }
            } else {
                pendingResult?.success(null) // 用户取消了选择
            }
            pendingResult = null
        }
    }
    
    private fun copyUriToExternalFilesDir(uri: Uri): String? {
        try {
            val contentResolver = context.contentResolver
            val fileName = getFileName(uri)
            val excelDir = File(context.getExternalFilesDir(null), "ExamApp")
            if (!excelDir.exists()) {
                excelDir.mkdirs()
            }
            
            val destFile = File(excelDir, fileName)
            
            contentResolver.openInputStream(uri)?.use { inputStream ->
                FileOutputStream(destFile).use { outputStream ->
                    inputStream.copyTo(outputStream)
                }
            }
            
            return destFile.absolutePath
        } catch (e: Exception) {
            Log.e("FileSelector", "复制文件失败: ${e.message}")
            return null
        }
    }
    
    private fun getFileName(uri: Uri): String {
        var fileName = "excel_file.xlsx"
        
        // 查询文件名
        val cursor = contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex != -1) {
                    fileName = it.getString(nameIndex)
                }
            }
        }
        
        return fileName
    }
}
